<?php
/**
 * Created by PhpStorm.
 * User: 12133
 * Date: 2024/8/29
 * Time: 11:17
 */

namespace app\controller\index;
use app\model\Customer AS model;
use app\model\index\Web AS web;
use app\model\CustomerKeywords AS keyword;
class Customer extends Base
{
    public function list(){
        $where[] = ['user_id','=',$this->user->id];
        $list = model::where($where)
            ->paginate([
                'page' => $this->page,
                'list_rows' => $this->size
            ]);
        return $this->view('/index/customer/list',['list' => $list]);
    }

    public function info($id){
        return $this->msg(model::with(['web','keywords'])->find($id));
    }

    public function save()
    {
        $id = input('id');
        $post = input('post.');
        if (!empty($id)) {
            $info = model::find($id);
            $data_type = input('type');
            if(!empty($data_type)){
                if ($data_type == 'web') {
                    web::create([
                        'web' => $post['data_web'],
                        'name' => $post['data_name'],
                        'user_id' => $this->user->id,
                        'customer_id' => $id,
                    ]);
                }elseif($data_type == 'keyword'){
                    keyword::create([
                        'keyword' => $post['data_keyword'],
                        'end_time' => $post['data_end_time'],
                        'user_id' => $this->user->id,
                        'customer_id' => $id,
                    ]);
                }else {
                    $array = [];
                    $images = json_decode($info->images);
                    if ($images == null)$images = [];
                    $images[] = $post['image'];
                    foreach ($images AS $key => $value)
                        if (empty($value))unset($images[$key]);
                    foreach ($images AS $key => $value)
                        $array[] = $value;
                    $info->save(['images' => json_encode($array)]);
                }
            }else {
                $info->save($post);
            }
        } else {
            $post['user_id'] = $this->user->id;
            $post['images'] = '[]';
            model::create($post);
        }
        return $this->msg();
    }

    public function del($type,$id){
        if($type == 'web'){
            web::where('id',$id)->delete();
        }else if($type == 'keyword'){
            keyword::where('id',$id)->delete();
        }else{
            $id = input('select_id');
            $info = model::find($id);
            $images = json_decode($info->images);
            unset($images[$id]);
            foreach ($images AS $key => $value)
                $array[] = $value;
            $info->save(['images' => json_encode($array)]);
        }
        return $this->msg();
    }
}